package com.newlink.building.common_base.activities

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.TextView
import com.google.gson.JsonSyntaxException
import com.newlink.building.common_base.R
import com.newlink.building.common_base.base.NL_BaseActivity
import com.newlink.building.common_base.databinding.ActivityWebviewBinding
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker

//import kotlinx.android.synthetic.main.activity_webview.*

/**
 * @Author: Jake
 * @Date: 2023-04-17
 * @Description:
 */
class NL_WebViewActivityNL : NL_BaseActivity() {

    companion object {
        /**
         * 对外开放统一入口
         *
         * @param context
         * @param url     url
         * @param title   title
         */
        fun startSelf(context: Context?, url: String, title: String) {
            val intent = Intent(context, NL_WebViewActivityNL::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.putExtra("link", url)
            intent.putExtra("title", title)
            context?.startActivity(intent)
        }
    }

    private lateinit var mBinding: ActivityWebviewBinding

    override fun attachLayoutRes(): View {
        mBinding = ActivityWebviewBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
    }

    override fun initView() {
        // WebView初始化时的安全混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("FvlWebViewActivity", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom("webview_init")

        initWebView(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        initWebView(intent)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mBinding.webview.canGoBack()) {
                mBinding.webview.goBack() //返回上个页面
                true
            } else {
                super.onKeyDown(keyCode, event)
            }
        } else super.onKeyDown(keyCode, event)
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun initWebView(intent: Intent?) {
        // WebView加载URL时的安全混淆
        Module_Obfuscation_ObfuscationHelper.beforeNetworkRequest(
            intent?.getStringExtra("link") ?: "",
            mapOf("type" to "WEBVIEW")
        )
        Module_Obfuscation_ObfuscationInvoker.invokeSpecific(22, "WEB_LOAD")

        intent?.let {
            val link = it.getStringExtra("link")
            findViewById<TextView>(R.id.tv_title_bar_center).text = it.getStringExtra("title")
            Log.e("webview_url", "webview activity 加载地址 is $link")
            link?.let { link ->
                if (link.contains("http")) {
                    mBinding.webview.settings.apply {
                        javaScriptEnabled = true
                        javaScriptCanOpenWindowsAutomatically = true
                        useWideViewPort = true
                        loadWithOverviewMode = true
                        cacheMode = WebSettings.LOAD_NO_CACHE
                        allowFileAccess = true
                        domStorageEnabled = true
                        databaseEnabled = true
                        setSupportZoom(true)
                        mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                    }
//                setAppCacheEnabled(true)
//                setAppCacheMaxSize((1024 * 1024 * 8).toLong())
//                setAppCachePath(applicationContext.cacheDir.absolutePath)
                    mBinding.webview.addJavascriptInterface(
                        JsInterface(),
                        "android"
                    )
                    // 添加 WebViewClient 以处理链接加载
                    mBinding.webview.webViewClient = object : android.webkit.WebViewClient() {
                        @SuppressLint("ObsoleteSdkInt")
                        override fun shouldOverrideUrlLoading(
                            view: WebView?,
                            url: String?
                        ): Boolean {
                            url?.let {
                                if (it.startsWith("http")) {
                                    // 让 WebView 继续加载该链接
                                    view?.loadUrl(it)
                                    return true
                                }
                            }
                            return super.shouldOverrideUrlLoading(view, url)
                        }
                    }
                }
                mBinding.webview.loadUrl(link)
                mBinding.webview.webChromeClient = MyWebChromeClient()
            }

        }
    }

    inner class MyWebChromeClient : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)

            if (newProgress == 100) {
                //加载完网页进度条消失
                mBinding.pbLoad.visibility = View.GONE
            } else {
                //开始加载网页时显示进度条
                mBinding.pbLoad.visibility = View.VISIBLE;
                //设置进度值
                mBinding.pbLoad.progress = newProgress;
            }
        }
    }

    internal class JsInterface {
        /**
         * h5分享
         */
        @JavascriptInterface
        fun webZhumuShare(params: String?) {
//            H5ShareBean bean = null;
            try {
//                bean = new Gson().fromJson(params, H5ShareBean.class);
            } catch (e: JsonSyntaxException) {
                e.printStackTrace()
            }
            //
//            if (bean == null) {
//                return;
//            }
//
//            UmShare.getInstance().shareH5Info(H5Activity.this, bean);
        }
    }


}